package com.theinit.ecommerce.factory;

import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.PropertyNamingStrategy;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class RestTemplateFactory {
	
	private static RestTemplate template = null;
	
	public static RestTemplate getTemplate() {
		if(template == null) 
			template = buildRestTemplate();
		return template;
	}
	
	private static RestTemplate buildRestTemplate() {
		MappingJacksonHttpMessageConverter messageConverter = new MappingJacksonHttpMessageConverter();
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
		//mapper.configure(DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS, false);
		//mapper.configure(DeserializationConfig.Feature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
		mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
		mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy());
		mapper.getSerializationConfig().withAnnotationIntrospector( new JacksonAnnotationIntrospector());
		messageConverter.setObjectMapper(mapper);	
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
		messageConverters.add(messageConverter);
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.setMessageConverters(messageConverters);
		return restTemplate;
	}
}